<template>
  <div class="schedule-management">
    <!-- 页面头部 -->
    <div class="header">
      <div class="header-left">
        <h2>赛程管理</h2>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>赛程管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-tooltip content="创建赛程" placement="top">
            <el-button type="primary" icon="Plus" @click="handleCreate">创建赛程</el-button>
          </el-tooltip>
          <el-tooltip content="日历视图" placement="top">
            <el-button type="success" icon="Calendar" @click="showCalendarView = true">日历视图</el-button>
          </el-tooltip>
          <el-tooltip content="导入赛程" placement="top">
            <el-button type="warning" icon="Upload" @click="handleImport">导入赛程</el-button>
          </el-tooltip>
          <el-tooltip content="导出赛程" placement="top">
            <el-button type="info" icon="Download" @click="handleExport">导出赛程</el-button>
          </el-tooltip>
          <el-tooltip content="刷新数据" placement="top">
            <el-button icon="Refresh" @click="fetchSchedules" :loading="loading">刷新</el-button>
          </el-tooltip>
        </el-button-group>
      </div>
    </div>

    <!-- 高级搜索区域 -->
    <div class="search-section">
      <el-card shadow="never" class="search-card">
        <template #header>
          <div class="search-header">
            <span class="search-title">
              <el-icon><Search /></el-icon>
              高级搜索
            </span>
            <el-button
              type="text"
              @click="toggleAdvancedSearch"
              :icon="showAdvancedSearch ? 'ArrowUp' : 'ArrowDown'"
            >
              {{ showAdvancedSearch ? '收起' : '展开' }}
            </el-button>
          </div>
        </template>

        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="项目名称">
                <el-select
                  v-model="searchForm.projectId"
                  placeholder="请选择项目"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="project.name"
                    :value="project.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="场地名称">
                <el-select
                  v-model="searchForm.venueId"
                  placeholder="请选择场地"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="venue in venueList"
                    :key="venue.id"
                    :label="venue.name"
                    :value="venue.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="赛程状态">
                <el-select v-model="searchForm.status" placeholder="请选择赛程状态" clearable style="width: 100%">
                  <el-option
                    v-for="status in scheduleStatuses"
                    :key="status"
                    :label="status"
                    :value="status"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="裁判">
                <el-select
                  v-model="searchForm.refereeId"
                  placeholder="请选择裁判"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="referee in refereeList"
                    :key="referee.id"
                    :label="referee.realName"
                    :value="referee.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-collapse-transition>
            <div v-show="showAdvancedSearch">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="日期范围">
                    <el-date-picker
                      v-model="searchForm.dateRange"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      format="YYYY-MM-DD HH:mm"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="轮次">
                    <el-input-number
                      v-model="searchForm.round"
                      :min="1"
                      :max="10"
                      placeholder="轮次"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="是否冲突">
                    <el-select v-model="searchForm.hasConflict" placeholder="请选择" clearable style="width: 100%">
                      <el-option label="有冲突" :value="true" />
                      <el-option label="无冲突" :value="false" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="时间筛选">
                    <el-select v-model="searchForm.timeFilter" placeholder="请选择" clearable style="width: 100%">
                      <el-option label="今日赛程" value="today" />
                      <el-option label="明日赛程" value="tomorrow" />
                      <el-option label="本周赛程" value="week" />
                      <el-option label="即将开始" value="upcoming" />
                      <el-option label="已结束" value="completed" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-transition>

          <el-row>
            <el-col :span="24" class="search-actions">
              <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
              <el-button icon="Refresh" @click="resetSearch">重置</el-button>
              <el-button type="success" icon="Plus" @click="handleQuickCreate">快速创建</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card total-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ stats.total }}</div>
              <div class="stats-label">总赛程</div>
              <div class="stats-trend">
                <el-icon v-if="stats.totalTrend > 0" color="#67C23A"><CaretTop /></el-icon>
                <el-icon v-else-if="stats.totalTrend < 0" color="#F56C6C"><CaretBottom /></el-icon>
                <span :class="stats.totalTrend >= 0 ? 'trend-up' : 'trend-down'">
                  {{ Math.abs(stats.totalTrend) }}%
                </span>
              </div>
            </div>
            <div class="stats-icon-wrapper">
              <el-icon class="stats-icon"><Calendar /></el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card today-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ stats.today }}</div>
              <div class="stats-label">今日赛程</div>
              <div class="stats-subtitle">{{ formatDate(new Date()) }}</div>
            </div>
            <div class="stats-icon-wrapper">
              <el-icon class="stats-icon"><Clock /></el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card progress-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ stats.inProgress }}</div>
              <div class="stats-label">进行中</div>
              <div class="stats-progress">
                <el-progress
                  :percentage="stats.inProgressPercentage"
                  :color="getProgressColor(stats.inProgressPercentage)"
                  :show-text="false"
                  :stroke-width="4"
                />
              </div>
            </div>
            <div class="stats-icon-wrapper">
              <el-icon class="stats-icon"><Timer /></el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card completed-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ stats.completed }}</div>
              <div class="stats-label">已完成</div>
              <div class="stats-subtitle">完成率 {{ stats.completionRate }}%</div>
            </div>
            <div class="stats-icon-wrapper">
              <el-icon class="stats-icon"><CircleCheck /></el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 冲突提醒卡片 -->
      <el-row v-if="conflictSchedules.length > 0" :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card class="conflict-card" shadow="never">
            <template #header>
              <div class="conflict-header">
                <el-icon class="conflict-icon" color="#F56C6C"><Warning /></el-icon>
                <span class="conflict-title">时间冲突提醒</span>
                <el-tag type="danger" size="small">{{ conflictSchedules.length }} 个冲突</el-tag>
                <el-button type="text" @click="handleViewConflicts">查看详情</el-button>
              </div>
            </template>
            <div class="conflict-content">
              <el-alert
                v-for="conflict in conflictSchedules.slice(0, 3)"
                :key="conflict.id"
                :title="conflict.description"
                type="warning"
                :closable="false"
                style="margin-bottom: 10px;"
              />
              <div v-if="conflictSchedules.length > 3" class="more-conflicts">
                还有 {{ conflictSchedules.length - 3 }} 个冲突...
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作区域 -->
    <div class="quick-actions">
      <el-card shadow="never">
        <template #header>
          <div class="quick-actions-header">
            <span>快速操作</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-button
              type="primary"
              :icon="Plus"
              @click="handleCreate"
              class="quick-action-btn"
              style="width: 100%"
            >
              创建赛程
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-button
              type="success"
              :icon="Calendar"
              @click="showCalendarView = true"
              class="quick-action-btn"
              style="width: 100%"
            >
              日历视图
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-button
              type="warning"
              :icon="Upload"
              @click="handleImport"
              class="quick-action-btn"
              style="width: 100%"
            >
              批量导入
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-button
              type="info"
              :icon="Download"
              @click="handleExport"
              class="quick-action-btn"
              style="width: 100%"
            >
              导出赛程
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-button
              type="primary"
              :icon="Setting"
              @click="handleVenueManagement"
              class="quick-action-btn"
              style="width: 100%"
            >
              场地管理
            </el-button>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-button
              type="success"
              :icon="User"
              @click="handleRefereeManagement"
              class="quick-action-btn"
              style="width: 100%"
            >
              裁判管理
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

  <!-- 赛程列表 -->
    <div class="schedule-list">
      <el-card shadow="never">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <span>赛程列表</span>
              <el-tag type="info" size="small">{{ pagination.total }} 条记录</el-tag>
            </div>
            <div class="table-actions">
              <el-dropdown @command="handleBatchAction" v-if="selectedSchedules.length > 0">
                <el-button type="primary">
                  批量操作 ({{ selectedSchedules.length }})
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="start" :disabled="!canBatchStart">
                      批量开始
                    </el-dropdown-item>
                    <el-dropdown-item command="end" :disabled="!canBatchEnd">
                      批量结束
                    </el-dropdown-item>
                    <el-dropdown-item command="postpone" :disabled="!canBatchPostpone">
                      批量延期
                    </el-dropdown-item>
                    <el-dropdown-item command="cancel" :disabled="!canBatchCancel" divided>
                      批量取消
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" :disabled="!canBatchDelete" style="color: #F56C6C;">
                      批量删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button-group>
                <el-button
                  :type="viewMode === 'table' ? 'primary' : 'default'"
                  @click="viewMode = 'table'"
                  icon="Grid"
                >
                  表格视图
                </el-button>
                <el-button
                  :type="viewMode === 'card' ? 'primary' : 'default'"
                  @click="viewMode = 'card'"
                  icon="List"
                >
                  卡片视图
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>

        <!-- 表格视图 -->
        <div v-if="viewMode === 'table'">
          <el-table
            v-loading="loading"
            :data="scheduleList"
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
            :default-sort="{ prop: 'startTime', order: 'ascending' }"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="赛程ID" width="80" sortable />

            <el-table-column label="项目信息" min-width="180">
              <template #default="{ row }">
                <div class="project-info">
                  <div class="project-name">
                    {{ row.project?.name || '-' }}
                    <el-tag v-if="row.hasConflict" type="danger" size="small" style="margin-left: 8px;">
                      冲突
                    </el-tag>
                  </div>
                  <div class="project-details">
                    <el-tag size="small" :type="getProjectTypeTagType(row.project?.type)">
                      {{ row.project?.type || '-' }}
                    </el-tag>
                    <span class="project-round">第{{ row.round }}轮</span>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="场地信息" min-width="150">
              <template #default="{ row }">
                <div class="venue-info">
                  <div class="venue-name">{{ row.venue?.name || '-' }}</div>
                  <div class="venue-location">{{ row.venue?.location || '-' }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="时间安排" min-width="200" sortable="custom" prop="startTime">
              <template #default="{ row }">
                <div class="time-info">
                  <div class="time-range">
                    {{ formatDateTime(row.startTime) }} - {{ formatDateTime(row.endTime) }}
                  </div>
                  <div class="duration">时长：{{ getDuration(row.startTime, row.endTime) }}</div>
                  <el-tag v-if="isToday(row.startTime)" type="success" size="small">
                    今日
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="裁判信息" min-width="120">
              <template #default="{ row }">
                <div v-if="row.referee" class="referee-info">
                  <div class="referee-name">{{ row.referee.realName }}</div>
                  <div class="referee-phone">{{ row.referee.phone }}</div>
                </div>
                <el-button
                  v-else
                  type="text"
                  size="small"
                  @click="handleAssignReferee(row)"
                >
                  分配裁判
                </el-button>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" width="100" sortable="custom">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-tooltip content="开始比赛" v-if="row.status === '未开始'">
                    <el-button
                      type="success"
                      size="small"
                      icon="VideoPlay"
                      @click="handleStart(row)"
                    />
                  </el-tooltip>
                  <el-tooltip content="结束比赛" v-if="row.status === '进行中'">
                    <el-button
                      type="warning"
                      size="small"
                      icon="VideoPause"
                      @click="handleEnd(row)"
                    />
                  </el-tooltip>
                  <el-tooltip content="延期比赛" v-if="row.status === '未开始' || row.status === '进行中'">
                    <el-button
                      type="info"
                      size="small"
                      icon="Clock"
                      @click="handlePostpone(row)"
                    />
                  </el-tooltip>
                  <el-tooltip content="取消比赛" v-if="canCancelSchedule(row)">
                    <el-button
                      type="danger"
                      size="small"
                      icon="Close"
                      @click="handleCancel(row)"
                    />
                  </el-tooltip>
                  <el-tooltip content="编辑赛程">
                    <el-button
                      type="primary"
                      size="small"
                      icon="Edit"
                      @click="handleEdit(row)"
                    />
                  </el-tooltip>
                  <el-tooltip content="查看详情">
                    <el-button
                      type="info"
                      size="small"
                      icon="View"
                      @click="handleViewDetails(row)"
                    />
                  </el-tooltip>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 卡片视图 -->
        <div v-else class="card-view">
          <el-row :gutter="20">
            <el-col
              v-for="schedule in scheduleList"
              :key="schedule.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <el-card class="schedule-card" shadow="hover" @click="handleViewDetails(schedule)">
                <template #header>
                  <div class="card-header">
                    <div class="card-title">
                      <span>{{ schedule.project?.name || '未命名赛程' }}</span>
                      <el-tag :type="getStatusTagType(schedule.status)" size="small">
                        {{ getStatusText(schedule.status) }}
                      </el-tag>
                    </div>
                    <el-checkbox
                      v-model="selectedSchedules"
                      :label="schedule.id"
                      @click.stop
                    />
                  </div>
                </template>

                <div class="card-content">
                  <div class="card-item">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDateTime(schedule.startTime) }}</span>
                  </div>
                  <div class="card-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ schedule.venue?.name || '未分配场地' }}</span>
                  </div>
                  <div class="card-item">
                    <el-icon><User /></el-icon>
                    <span>{{ schedule.referee?.realName || '未分配裁判' }}</span>
                  </div>
                  <div class="card-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ getDuration(schedule.startTime, schedule.endTime) }}</span>
                  </div>
                </div>

                <div class="card-footer">
                  <el-button-group size="small">
                    <el-button
                      v-if="schedule.status === '未开始'"
                      type="success"
                      icon="VideoPlay"
                      @click.stop="handleStart(schedule)"
                    />
                    <el-button
                      v-if="schedule.status === '进行中'"
                      type="warning"
                      icon="VideoPause"
                      @click.stop="handleEnd(schedule)"
                    />
                    <el-button
                      type="primary"
                      icon="Edit"
                      @click.stop="handleEdit(schedule)"
                    />
                    <el-button
                      type="info"
                      icon="View"
                      @click.stop="handleViewDetails(schedule)"
                    />
                  </el-button-group>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑赛程对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      :title="isEditing ? '编辑赛程' : '创建赛程'"
      width="800px"
      @close="resetScheduleForm"
      :close-on-click-modal="false"
    >
      <el-form
        ref="scheduleFormRef"
        :model="scheduleForm"
        :rules="scheduleFormRules"
        label-width="120px"
      >
        <el-tabs v-model="activeTab" class="schedule-form-tabs">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectId">
                  <el-select
                    v-model="scheduleForm.projectId"
                    placeholder="请选择项目"
                    style="width: 100%"
                    filterable
                    @change="handleProjectChange"
                  >
                    <el-option
                      v-for="project in projectList"
                      :key="project.id"
                      :label="`${project.name} (${project.type})`"
                      :value="project.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="场地名称" prop="venueId">
                  <el-select
                    v-model="scheduleForm.venueId"
                    placeholder="请选择场地"
                    style="width: 100%"
                    filterable
                    @change="handleVenueChange"
                  >
                    <el-option
                      v-for="venue in venueList"
                      :key="venue.id"
                      :label="`${venue.name} - ${venue.location}`"
                      :value="venue.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="轮次" prop="round">
                  <el-input-number
                    v-model="scheduleForm.round"
                    :min="1"
                    :max="10"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预计时长">
                  <el-input-number
                    v-model="scheduleForm.duration"
                    :min="30"
                    :max="480"
                    :step="30"
                    style="width: 100%"
                    @change="handleDurationChange"
                  />
                  <span style="margin-left: 10px;">分钟</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="scheduleForm.startTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    @change="handleTimeChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="scheduleForm.endTime"
                    type="datetime"
                    placeholder="请选择结束时间"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    @change="handleTimeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 时间冲突检测 -->
            <el-form-item v-if="timeConflict.length > 0" label="冲突检测">
              <el-alert
                v-for="conflict in timeConflict"
                :key="conflict.id"
                :title="conflict.description"
                type="warning"
                :closable="false"
                style="margin-bottom: 10px"
              />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="人员安排" name="personnel">
            <el-form-item label="主裁判">
              <el-select
                v-model="scheduleForm.refereeId"
                placeholder="请选择主裁判（可选）"
                style="width: 100%"
                filterable
                clearable
                @change="handleRefereeChange"
              >
                <el-option
                  v-for="referee in refereeList"
                  :key="referee.id"
                  :label="`${referee.realName} (${referee.phone})`"
                  :value="referee.id"
                />
              </el-select>
            </el-form-item>

            <!-- 裁判可用性检测 -->
            <el-form-item v-if="refereeConflict.length > 0" label="裁判状态">
              <el-alert
                v-for="conflict in refereeConflict"
                :key="conflict.id"
                :title="conflict.description"
                type="warning"
                :closable="false"
                style="margin-bottom: 10px"
              />
            </el-form-item>

            <el-form-item label="助理裁判">
              <el-select
                v-model="scheduleForm.assistantReferees"
                placeholder="请选择助理裁判（可选）"
                style="width: 100%"
                filterable
                multiple
                clearable
              >
                <el-option
                  v-for="referee in refereeList"
                  :key="referee.id"
                  :label="`${referee.realName} (${referee.phone})`"
                  :value="referee.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="工作人员">
              <el-select
                v-model="scheduleForm.staffIds"
                placeholder="请选择工作人员（可选）"
                style="width: 100%"
                filterable
                multiple
                clearable
              >
                <el-option
                  v-for="staff in staffList"
                  :key="staff.id"
                  :label="`${staff.realName} (${staff.role})`"
                  :value="staff.id"
                />
              </el-select>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="其他设置" name="settings">
            <el-form-item label="备注">
              <el-input
                v-model="scheduleForm.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>

            <el-form-item label="重要程度">
              <el-radio-group v-model="scheduleForm.priority">
                <el-radio-button label="low">低</el-radio-button>
                <el-radio-button label="medium">中</el-radio-button>
                <el-radio-button label="high">高</el-radio-button>
                <el-radio-button label="urgent">紧急</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="是否公开">
              <el-switch
                v-model="scheduleForm.isPublic"
                active-text="公开"
                inactive-text="私密"
              />
            </el-form-item>

            <el-form-item label="允许报名">
              <el-switch
                v-model="scheduleForm.allowRegistration"
                active-text="允许"
                inactive-text="不允许"
              />
            </el-form-item>

            <el-form-item label="最大参与人数" v-if="scheduleForm.allowRegistration">
              <el-input-number
                v-model="scheduleForm.maxParticipants"
                :min="1"
                :max="1000"
                style="width: 100%"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">取消</el-button>
          <el-button @click="handleSaveAndCreate" :loading="saveLoading">
            保存并创建
          </el-button>
          <el-button type="primary" @click="handleSaveSchedule" :loading="saveLoading">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="赛程详情"
      width="700px"
    >
      <div v-if="selectedSchedule" class="schedule-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="赛程ID">{{ selectedSchedule.id }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedSchedule.status)">
              {{ getStatusText(selectedSchedule.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="项目名称">{{ selectedSchedule.project?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="项目类型">{{ selectedSchedule.project?.type || '-' }}</el-descriptions-item>
          <el-descriptions-item label="场地名称">{{ selectedSchedule.venue?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="场地位置">{{ selectedSchedule.venue?.location || '-' }}</el-descriptions-item>
          <el-descriptions-item label="轮次">{{ selectedSchedule.round }}</el-descriptions-item>
          <el-descriptions-item label="主裁判">{{ selectedSchedule.referee?.realName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(selectedSchedule.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(selectedSchedule.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="比赛时长" :span="2">
            {{ getDuration(selectedSchedule.startTime, selectedSchedule.endTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(selectedSchedule.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 延期对话框 -->
    <el-dialog
      v-model="postponeDialogVisible"
      title="延期比赛"
      width="500px"
      @close="resetPostponeForm"
    >
      <el-form
        ref="postponeFormRef"
        :model="postponeForm"
        :rules="postponeFormRules"
        label-width="100px"
      >
        <el-form-item label="比赛名称">
          <el-input v-model="postponeForm.matchName" disabled />
        </el-form-item>
        <el-form-item label="新开始时间" prop="newStartTime">
          <el-date-picker
            v-model="postponeForm.newStartTime"
            type="datetime"
            placeholder="请选择新的开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="新结束时间" prop="newEndTime">
          <el-date-picker
            v-model="postponeForm.newEndTime"
            type="datetime"
            placeholder="请选择新的结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="postponeDialogVisible = false">取消</el-button>
          <el-button type="warning" @click="handleConfirmPostpone" :loading="postponeLoading">
            确认延期
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 日历视图组件 -->
    <ScheduleCalendar
      v-if="showCalendarView"
      v-model="showCalendarView"
      @schedule-updated="fetchSchedules"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Calendar,
  Clock,
  Timer,
  CircleCheck,
  Plus,
  Search,
  CaretTop,
  CaretBottom,
  Warning,
  Setting,
  User,
  Upload,
  Download,
  Location,
  ArrowDown
} from '@element-plus/icons-vue'
import {
  getSchedulePage,
  createSchedule,
  updateSchedule,
  startSchedule,
  endSchedule,
  postponeSchedule,
  cancelSchedule,
  assignReferee,
  getScheduleStatuses,
  checkVenueAvailability,
  checkRefereeAvailability,
  batchUpdateScheduleStatus,
  exportSchedule
} from '@/api/schedule'
import { getProjectPage } from '@/api/project'
import { getUsersByRoleId } from '@/api/user'
import ScheduleCalendar from './components/ScheduleCalendar.vue'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const postponeLoading = ref(false)
const scheduleList = ref([])
const selectedSchedule = ref(null)
const projectList = ref([])
const venueList = ref([])
const refereeList = ref([])
const staffList = ref([])
const scheduleStatuses = ref([])
const showCalendarView = ref(false)
const conflictSchedules = ref([])
const timeConflict = ref([])
const refereeConflict = ref([])
const viewMode = ref('table') // 'table' 或 'card'
const showAdvancedSearch = ref(false)
const selectedSchedules = ref([])
const activeTab = ref('basic')

// 对话框状态
const scheduleDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const postponeDialogVisible = ref(false)
const isEditing = ref(false)

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 排序参数
const sortParams = reactive({
  prop: 'startTime',
  order: 'ascending'
})

// 搜索表单
const searchForm = reactive({
  projectId: null,
  venueId: null,
  refereeId: null,
  status: '',
  dateRange: [],
  round: null,
  hasConflict: null,
  timeFilter: ''
})

// 赛程表单
const scheduleFormRef = ref()
const scheduleForm = reactive({
  id: null,
  projectId: null,
  venueId: null,
  round: 1,
  startTime: '',
  endTime: '',
  refereeId: null,
  assistantReferees: [],
  staffIds: [],
  duration: 60,
  remarks: '',
  priority: 'medium',
  isPublic: true,
  allowRegistration: false,
  maxParticipants: 100
})

// 延期表单
const postponeFormRef = ref()
const postponeForm = reactive({
  scheduleId: null,
  matchName: '',
  newStartTime: '',
  newEndTime: ''
})

// 表单验证规则
const scheduleFormRules = {
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  venueId: [
    { required: true, message: '请选择场地', trigger: 'change' }
  ],
  round: [
    { required: true, message: '请输入轮次', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '轮次应在1-10之间', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

const postponeFormRules = {
  newStartTime: [
    { required: true, message: '请选择新的开始时间', trigger: 'change' }
  ],
  newEndTime: [
    { required: true, message: '请选择新的结束时间', trigger: 'change' }
  ]
}

// 计算属性 - 批量操作权限
const canBatchStart = computed(() => {
  return selectedSchedules.value.length > 0 &&
         selectedSchedules.value.every(id => {
           const schedule = scheduleList.value.find(s => s.id === id)
           return schedule && schedule.status === '未开始'
         })
})

const canBatchEnd = computed(() => {
  return selectedSchedules.value.length > 0 &&
         selectedSchedules.value.every(id => {
           const schedule = scheduleList.value.find(s => s.id === id)
           return schedule && schedule.status === '进行中'
         })
})

const canBatchPostpone = computed(() => {
  return selectedSchedules.value.length > 0 &&
         selectedSchedules.value.every(id => {
           const schedule = scheduleList.value.find(s => s.id === id)
           return schedule && (schedule.status === '未开始' || schedule.status === '进行中')
         })
})

const canBatchCancel = computed(() => {
  return selectedSchedules.value.length > 0 &&
         selectedSchedules.value.every(id => {
           const schedule = scheduleList.value.find(s => s.id === id)
           return schedule && canCancelSchedule(schedule)
         })
})

const canBatchDelete = computed(() => {
  return selectedSchedules.value.length > 0 &&
         selectedSchedules.value.every(id => {
           const schedule = scheduleList.value.find(s => s.id === id)
           return schedule && schedule.status !== '进行中'
         })
})

// 统计数据 - 增强版
const stats = computed(() => {
  const today = new Date()
  const todayStr = today.toDateString()

  const todaySchedules = scheduleList.value.filter(item => {
    const itemDate = new Date(item.startTime).toDateString()
    return itemDate === todayStr
  })

  const total = scheduleList.value.length
  const completed = scheduleList.value.filter(item => item.status === '已结束').length
  const inProgress = scheduleList.value.filter(item => item.status === '进行中').length
  const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0

  // 模拟趋势数据（实际应该从API获取）
  const totalTrend = Math.floor(Math.random() * 20) - 10 // -10 到 10
  const inProgressPercentage = total > 0 ? Math.round((inProgress / total) * 100) : 0

  return {
    total,
    today: todaySchedules.length,
    inProgress,
    completed,
    completionRate,
    totalTrend,
    inProgressPercentage,
    pending: scheduleList.value.filter(item => item.status === '未开始').length,
    cancelled: scheduleList.value.filter(item => item.status === '取消').length
  }
})

// 工具方法 - 增强版
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    month: 'long',
    day: 'numeric'
  })
}

const getDuration = (startTime, endTime) => {
  if (!startTime || !endTime) return '-'
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diff = end - start
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  return `${hours}小时${minutes}分钟`
}

const isToday = (dateTime) => {
  if (!dateTime) return false
  const today = new Date().toDateString()
  const date = new Date(dateTime).toDateString()
  return today === date
}

const canCancelSchedule = (schedule) => {
  return schedule.status !== '已结束' && schedule.status !== '取消'
}

const getProgressColor = (percentage) => {
  if (percentage < 30) return '#67C23A'
  if (percentage < 70) return '#E6A23C'
  return '#F56C6C'
}

// 冲突检测方法
const checkTimeConflicts = async (venueId, startTime, endTime, excludeId = null) => {
  try {
    const response = await checkVenueAvailability(venueId, startTime, endTime, excludeId)
    if (response.code === 200) {
      timeConflict.value = response.data.conflicts || []
    }
  } catch (error) {
    // 时间冲突检查失败处理
    timeConflict.value = []
  }
}

const checkRefereeConflicts = async (refereeId, startTime, endTime, excludeId = null) => {
  try {
    const response = await checkRefereeAvailability(refereeId, startTime, endTime, excludeId)
    if (response.code === 200) {
      refereeConflict.value = response.data.conflicts || []
    }
  } catch (error) {
    // 裁判冲突检查失败处理
    refereeConflict.value = []
  }
}

const fetchConflicts = async () => {
  try {
    // 这里应该调用API获取冲突数据
    conflictSchedules.value = []
  } catch (error) {
    // 冲突数据获取失败处理
  }
}

const getStatusTagType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '进行中': 'warning',
    '已结束': 'success',
    '延期': 'warning',
    '取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    '未开始': '未开始',
    '进行中': '进行中',
    '已结束': '已结束',
    '延期': '延期',
    '取消': '取消'
  }
  return statusMap[status] || status
}

const getProjectTypeTagType = (type) => {
  const typeMap = {
    '径赛': 'primary',
    '田赛': 'success',
    '球类': 'warning',
    '其他': 'info'
  }
  return typeMap[type] || 'info'
}

// API调用方法 - 增强版
const fetchSchedules = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    delete params.dateRange

    // 处理时间筛选
    if (searchForm.timeFilter) {
      const now = new Date()
      switch (searchForm.timeFilter) {
        case 'today': {
          params.startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString()
          params.endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).toISOString()
          break
        }
        case 'tomorrow': {
          const tomorrow = new Date(now)
          tomorrow.setDate(tomorrow.getDate() + 1)
          params.startDate = new Date(tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate()).toISOString()
          params.endDate = new Date(tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate() + 1).toISOString()
          break
        }
        case 'week': {
          const weekStart = new Date(now)
          weekStart.setDate(now.getDate() - now.getDay())
          const weekEnd = new Date(weekStart)
          weekEnd.setDate(weekStart.getDate() + 7)
          params.startDate = weekStart.toISOString()
          params.endDate = weekEnd.toISOString()
          break
        }
        case 'upcoming':
          params.startDate = now.toISOString()
          break
        case 'completed':
          params.endDate = now.toISOString()
          break
      }
    }

    // 添加排序参数
    params.sortBy = sortParams.prop
    params.sortOrder = sortParams.order === 'ascending' ? 'asc' : 'desc'

    const response = await getSchedulePage(pagination.currentPage, pagination.pageSize, params)

    if (response.code === 200) {
      scheduleList.value = response.data.records || []
      pagination.total = response.data.total || 0

      // 检测冲突
      await fetchConflicts()
    } else {
      ElMessage.error(response.message || '获取赛程列表失败')
    }
  } catch (error) {
    // 赛程列表获取失败处理
    ElMessage.error('获取赛程列表失败')
  } finally {
    loading.value = false
  }
}

const fetchProjects = async () => {
  try {
    const response = await getProjectPage(1, 1000, {})
    if (response.code === 200) {
      projectList.value = response.data.records || []
    }
  } catch (error) {
    // 项目列表获取失败处理
  }
}

const fetchVenues = async () => {
  try {
    // 这里应该调用场地API，暂时使用模拟数据
    venueList.value = [
      { id: 1, name: '田径场', location: '学校东门北侧', capacity: 500, type: '室外' },
      { id: 2, name: '篮球场', location: '图书馆南侧', capacity: 200, type: '室外' },
      { id: 3, name: '体育馆', location: '学校中心区域', capacity: 1000, type: '室内' },
      { id: 4, name: '游泳馆', location: '体育中心西侧', capacity: 300, type: '室内' },
      { id: 5, name: '网球场', location: '南区运动场', capacity: 100, type: '室外' }
    ]
  } catch (error) {
    // 场地列表获取失败处理
  }
}

const fetchReferees = async () => {
  try {
    const response = await getUsersByRoleId('裁判')
    if (response.code === 200) {
      refereeList.value = response.data || []
    }
  } catch (error) {
    // 裁判列表获取失败处理
  }
}

const fetchStaff = async () => {
  try {
    // 模拟工作人员数据
    staffList.value = [
      { id: 1, realName: '张三', role: '计时员', phone: '13800138001' },
      { id: 2, realName: '李四', role: '记录员', phone: '13800138002' },
      { id: 3, realName: '王五', role: '医疗员', phone: '13800138003' },
      { id: 4, realName: '赵六', role: '安保员', phone: '13800138004' }
    ]
  } catch (error) {
    // 工作人员列表获取失败处理
  }
}

const fetchScheduleStatuses = async () => {
  try {
    const response = await getScheduleStatuses()
    if (response.code === 200) {
      scheduleStatuses.value = response.data || ['未开始', '进行中', '已结束', '延期', '取消']
    }
  } catch (error) {
    // 赛程状态获取失败处理
    scheduleStatuses.value = ['未开始', '进行中', '已结束', '延期', '取消']
  }
}

// 事件处理方法 - 增强版
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchSchedules()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    projectId: null,
    venueId: null,
    refereeId: null,
    status: '',
    dateRange: [],
    round: null,
    hasConflict: null,
    timeFilter: ''
  })
  handleSearch()
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchSchedules()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchSchedules()
}

const handleSortChange = ({ prop, order }) => {
  sortParams.prop = prop
  sortParams.order = order
  fetchSchedules()
}

const handleSelectionChange = (selection) => {
  selectedSchedules.value = selection.map(item => item.id)
}

const handleCreate = () => {
  isEditing.value = false
  resetScheduleForm()
  scheduleDialogVisible.value = true
}

const handleQuickCreate = () => {
  isEditing.value = false
  // 设置默认值
  resetScheduleForm()
  scheduleForm.startTime = new Date().toISOString().slice(0, 16).replace('T', ' ')
  const endTime = new Date()
  endTime.setHours(endTime.getHours() + 2)
  scheduleForm.endTime = endTime.toISOString().slice(0, 16).replace('T', ' ')
  scheduleDialogVisible.value = true
}

// 表单变化处理
const handleProjectChange = (projectId) => {
  const project = projectList.value.find(p => p.id === projectId)
  if (project) {
    // 根据项目类型设置默认时长
    switch (project.type) {
      case '径赛':
        scheduleForm.duration = 30
        break
      case '田赛':
        scheduleForm.duration = 90
        break
      case '球类':
        scheduleForm.duration = 120
        break
      default:
        scheduleForm.duration = 60
    }
    handleDurationChange(scheduleForm.duration)
  }
}

const handleVenueChange = () => {
  if (scheduleForm.venueId && scheduleForm.startTime && scheduleForm.endTime) {
    checkTimeConflicts(scheduleForm.venueId, scheduleForm.startTime, scheduleForm.endTime, scheduleForm.id)
  }
}

const handleRefereeChange = () => {
  if (scheduleForm.refereeId && scheduleForm.startTime && scheduleForm.endTime) {
    checkRefereeConflicts(scheduleForm.refereeId, scheduleForm.startTime, scheduleForm.endTime, scheduleForm.id)
  }
}

const handleDurationChange = (duration) => {
  if (scheduleForm.startTime && duration) {
    const endTime = new Date(scheduleForm.startTime)
    endTime.setMinutes(endTime.getMinutes() + duration)
    scheduleForm.endTime = endTime.toISOString().slice(0, 19).replace('T', ' ')
  }
}

const handleTimeChange = () => {
  if (scheduleForm.startTime && scheduleForm.endTime) {
    if (scheduleForm.venueId) {
      checkTimeConflicts(scheduleForm.venueId, scheduleForm.startTime, scheduleForm.endTime, scheduleForm.id)
    }
    if (scheduleForm.refereeId) {
      checkRefereeConflicts(scheduleForm.refereeId, scheduleForm.startTime, scheduleForm.endTime, scheduleForm.id)
    }
  }
}

// 批量操作
const handleBatchAction = async (action) => {
  try {
    let message = ''
    let apiCall = null

    switch (action) {
      case 'start':
        message = '确定要开始选中的赛程吗？'
        apiCall = () => batchUpdateScheduleStatus(selectedSchedules.value, '进行中')
        break
      case 'end':
        message = '确定要结束选中的赛程吗？'
        apiCall = () => batchUpdateScheduleStatus(selectedSchedules.value, '已结束')
        break
      case 'postpone':
        message = '确定要延期选中的赛程吗？'
        // 这里可以添加延期对话框
        return
      case 'cancel':
        message = '确定要取消选中的赛程吗？'
        apiCall = () => batchUpdateScheduleStatus(selectedSchedules.value, '取消')
        break
      case 'delete':
        message = '确定要删除选中的赛程吗？此操作不可恢复！'
        // 这里应该添加批量删除API
        return
    }

    await ElMessageBox.confirm(message, '批量操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true
    const response = await apiCall()

    if (response.code === 200) {
      ElMessage.success('批量操作成功')
      selectedSchedules.value = []
      fetchSchedules()
    } else {
      ElMessage.error(response.message || '批量操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 批量操作失败处理
      ElMessage.error('批量操作失败')
    }
  } finally {
    loading.value = false
  }
}

// 导入导出功能
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

const handleExport = async () => {
  try {
    loading.value = true
    const response = await exportSchedule(searchForm)

    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `赛程表_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    // 导出功能失败处理
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 查看冲突详情
const handleViewConflicts = () => {
  ElMessage.info('冲突详情功能开发中...')
}

// 场地管理和裁判管理
const handleVenueManagement = () => {
  ElMessage.info('场地管理功能开发中...')
}

const handleRefereeManagement = () => {
  ElMessage.info('裁判管理功能开发中...')
}

// 保存并创建新赛程
const handleSaveAndCreate = async () => {
  await handleSaveSchedule()
  if (!saveLoading.value) {
    handleCreate()
  }
}

const handleEdit = (schedule) => {
  isEditing.value = true
  Object.assign(scheduleForm, {
    id: schedule.id,
    projectId: schedule.projectId,
    venueId: schedule.venueId,
    round: schedule.round,
    startTime: schedule.startTime,
    endTime: schedule.endTime,
    refereeId: schedule.refereeId
  })
  scheduleDialogVisible.value = true
}

const handleViewDetails = (schedule) => {
  selectedSchedule.value = schedule
  detailDialogVisible.value = true
}

const handleSaveSchedule = async () => {
  try {
    await scheduleFormRef.value.validate()

    // 检查时间逻辑
    if (new Date(scheduleForm.endTime) <= new Date(scheduleForm.startTime)) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    saveLoading.value = true

    const response = isEditing.value
      ? await updateSchedule(scheduleForm)
      : await createSchedule(scheduleForm)

    if (response.code === 200) {
      ElMessage.success(isEditing.value ? '更新成功' : '创建成功')
      scheduleDialogVisible.value = false
      fetchSchedules()
    } else {
      ElMessage.error(response.message || (isEditing.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    if (error.name !== 'ElFormValidateError') {
      // 保存赛程失败处理
      ElMessage.error('保存失败')
    }
  } finally {
    saveLoading.value = false
  }
}

const handleStart = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始「${schedule.project?.name}」的比赛吗？`,
      '确认开始',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await startSchedule(schedule.id)
    if (response.code === 200) {
      ElMessage.success('比赛已开始')
      fetchSchedules()
    } else {
      ElMessage.error(response.message || '开始比赛失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 开始比赛失败处理
      ElMessage.error('开始比赛失败')
    }
  }
}

const handleEnd = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      `确定要结束「${schedule.project?.name}」的比赛吗？`,
      '确认结束',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await endSchedule(schedule.id)
    if (response.code === 200) {
      ElMessage.success('比赛已结束')
      fetchSchedules()
    } else {
      ElMessage.error(response.message || '结束比赛失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 结束比赛失败处理
      ElMessage.error('结束比赛失败')
    }
  }
}

const handlePostpone = (schedule) => {
  postponeForm.scheduleId = schedule.id
  postponeForm.matchName = schedule.project?.name || ''
  postponeForm.newStartTime = ''
  postponeForm.newEndTime = ''
  postponeDialogVisible.value = true
}

const handleConfirmPostpone = async () => {
  try {
    await postponeFormRef.value.validate()

    // 检查时间逻辑
    if (new Date(postponeForm.newEndTime) <= new Date(postponeForm.newStartTime)) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    postponeLoading.value = true

    const response = await postponeSchedule(
      postponeForm.scheduleId,
      postponeForm.newStartTime,
      postponeForm.newEndTime
    )

    if (response.code === 200) {
      ElMessage.success('比赛已延期')
      postponeDialogVisible.value = false
      fetchSchedules()
    } else {
      ElMessage.error(response.message || '延期失败')
    }
  } catch (error) {
    if (error.name !== 'ElFormValidateError') {
      // 延期比赛失败处理
      ElMessage.error('延期失败')
    }
  } finally {
    postponeLoading.value = false
  }
}

const handleCancel = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消「${schedule.project?.name}」的比赛吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await cancelSchedule(schedule.id)
    if (response.code === 200) {
      ElMessage.success('比赛已取消')
      fetchSchedules()
    } else {
      ElMessage.error(response.message || '取消比赛失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 取消比赛失败处理
      ElMessage.error('取消比赛失败')
    }
  }
}

const handleAssignReferee = async (schedule) => {
  try {
    const { value: refereeId } = await ElMessageBox.prompt(
      '请选择裁判',
      '分配裁判',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'select',
        inputOptions: refereeList.value.map(referee => ({
          label: referee.realName,
          value: referee.id
        }))
      }
    )

    if (refereeId) {
      const response = await assignReferee(schedule.id, refereeId)
      if (response.code === 200) {
        ElMessage.success('裁判分配成功')
        fetchSchedules()
      } else {
        ElMessage.error(response.message || '分配失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 分配裁判失败处理
      ElMessage.error('分配失败')
    }
  }
}

const resetScheduleForm = () => {
  scheduleFormRef.value?.resetFields()
  Object.assign(scheduleForm, {
    id: null,
    projectId: null,
    venueId: null,
    round: 1,
    startTime: '',
    endTime: '',
    refereeId: null,
    assistantReferees: [],
    staffIds: [],
    duration: 60,
    remarks: '',
    priority: 'medium',
    isPublic: true,
    allowRegistration: false,
    maxParticipants: 100
  })
  timeConflict.value = []
  refereeConflict.value = []
  activeTab.value = 'basic'
}

const resetPostponeForm = () => {
  postponeFormRef.value?.resetFields()
  Object.assign(postponeForm, {
    scheduleId: null,
    matchName: '',
    newStartTime: '',
    newEndTime: ''
  })
}

// 生命周期钩子 - 增强版
onMounted(() => {
  fetchSchedules()
  fetchProjects()
  fetchVenues()
  fetchReferees()
  fetchStaff()
  fetchScheduleStatuses()
  fetchConflicts()
})

// 监听搜索表单变化
watch(searchForm, () => {
  // 可以添加自动搜索的防抖逻辑
}, { deep: true })

// 监听选中赛程变化
watch(selectedSchedules, (newVal) => {
  if (newVal.length === 0) {
    // 清空选中时的处理
  }
})
</script>

<style scoped>
/* 主容器样式 */
.schedule-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 页面头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 4px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-right .el-button-group {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.search-title .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.search-form {
  margin: 0;
}

.search-actions {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  margin-top: 16px;
}

.search-actions .el-button {
  margin: 0 8px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 24px;
}

.stats-card {
  position: relative;
  overflow: hidden;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  border: none;
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.stats-content {
  position: relative;
  z-index: 2;
  padding: 16px;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1.2;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stats-subtitle {
  font-size: 12px;
  color: #c0c4cc;
}

.stats-trend {
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-up {
  color: #67c23a;
  font-weight: 600;
}

.trend-down {
  color: #f56c6c;
  font-weight: 600;
}

.stats-progress {
  margin-top: 12px;
}

.stats-icon-wrapper {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
}

.stats-icon {
  font-size: 48px;
  opacity: 0.15;
}

/* 不同类型统计卡片颜色 */
.total-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.total-card .stats-number,
.total-card .stats-label,
.total-card .stats-subtitle {
  color: white;
}

.today-card {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.today-card .stats-number,
.today-card .stats-label,
.today-card .stats-subtitle {
  color: white;
}

.progress-card {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.progress-card .stats-number,
.progress-card .stats-label,
.progress-card .stats-subtitle {
  color: white;
}

.completed-card {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.completed-card .stats-number,
.completed-card .stats-label,
.completed-card .stats-subtitle {
  color: white;
}

/* 冲突提醒卡片样式 */
.conflict-card {
  border-left: 4px solid #f56c6c;
  border-radius: 8px;
}

.conflict-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.conflict-icon {
  font-size: 18px;
}

.conflict-title {
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.conflict-content {
  padding: 0;
}

.more-conflicts {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 8px;
}

/* 快速操作区域样式 */
.quick-actions {
  margin-bottom: 24px;
}

.quick-actions-header {
  font-weight: 600;
  color: #303133;
}

.quick-action-btn {
  margin-bottom: 12px;
  height: 48px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.quick-action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 赛程列表样式 */
.schedule-list {
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title span {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 卡片视图样式 */
.card-view {
  min-height: 400px;
}

.schedule-card {
  border-radius: 12px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #e4e7ed;
}

.schedule-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
  border-color: #409eff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.card-title span {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
}

.card-content {
  padding: 16px 0;
}

.card-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  color: #606266;
  font-size: 14px;
}

.card-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.card-footer {
  padding: 16px 0 0 0;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: #fafafa;
  font-weight: 600;
  color: #303133;
}

.project-info,
.venue-info,
.time-info,
.referee-info {
  line-height: 1.6;
}

.project-name,
.venue-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  font-size: 14px;
}

.project-details {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.project-round {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
}

.venue-location,
.referee-phone {
  font-size: 12px;
  color: #909399;
}

.time-range {
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  font-size: 14px;
}

.duration {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.referee-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

/* 分页样式 */
.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
}

/* 表单样式优化 */
.schedule-form-tabs {
  margin: -20px;
}

.schedule-form-tabs :deep(.el-tabs__header) {
  margin: 0;
  background: #fafafa;
  padding: 0 20px;
}

.schedule-form-tabs :deep(.el-tabs__content) {
  padding: 20px;
}

/* 详情对话框样式 */
.schedule-detail {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 标签样式优化 */
.el-tag {
  margin: 2px;
  border-radius: 4px;
  font-weight: 500;
}

/* 按钮组样式优化 */
.el-button-group .el-button {
  border-radius: 0;
}

.el-button-group .el-button:first-child {
  border-radius: 4px 0 0 4px;
}

.el-button-group .el-button:last-child {
  border-radius: 0 4px 4px 0;
}


/* 动画效果 */
.el-card {
  transition: all 0.3s ease;
}

.el-button {
  transition: all 0.3s ease;
}

.el-table__row {
  transition: all 0.3s ease;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.el-dialog__header {
  background: #fafafa;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__title {
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  background: #fafafa;
  border-top: 1px solid #ebeef5;
}
</style>